# To change this template, choose Tools | Templates
# and open the template in the editor.
require 'PeerRecord'
class PeerTable
  attr_reader :file_name, :max_size, :peers
  def initialize(file, max_size) #max_size should accept -1 as infinate
    @peers = Array.new
    @file_name = file
    table_lines = IO.readlines(file)[0..max_size]
    #TODO: add a version line to the begining of the file
    for line in table_lines
      @peers.push(PeerRecord.new(self,line.split(':')[1],line.split(':')[2], line.split(':')[0],line.split(':')[3],line.split(':')[4]))
    end
  end
  def add_peer(ip, port)
    @peers.push(PeerRecord.new(self, ip, port))
  end
  def connection_success(ip, port)
    #TODO: must check out scope in Ruby
    changed = false
    for p in @peers
      if p.ip == ip && p.port == port
        p.connection
        changed = true
      end
    end
    @peers.push(PeerRecord.new(self,ip,port))
  end
  def connection_fail(ip, port, record_new)
    changed = false
    for p in @peers
      if p.ip == ip && p.port = port
        p.connection(false)
      end
    end
    @peers.push(PeerRecord.new(self,ip,port,1,0)) if record_new
  end
  def save_table(file=@file_name)
    #this changes the type of the variable
    file = File.new(file)
    for peer in @peers
      file.puts(peer.name, peer.ip, peer.port, peer.connection_attempts, peer.connection_sucesses)
    end
    file.close
  end
end